__author__ = 'Pierre Moermans'

from django.http import HttpResponse
from django.shortcuts import render_to_response, redirect
from django.core.exceptions import ObjectDoesNotExist
import json
import logging
import uuid

from pyfacture import models
from pyfacture import message

logger = logging.getLogger(__name__)

class CustomerDecoder(json.JSONDecoder):
    def decode(self, s):
        customer_dict = json.loads(s)
        customer = models.Customer()
        customer.name = customer_dict['name']
        return customer

def autocomplete(request):
    text = request.GET['term']

    customers = []
    try:
        customers = list(models.Customer.objects.filter(name__icontains = text))
    except Exception, e:
        return message.buildInfo("no customer with " + text + " in its name")

    json_response=[]
    for customer in customers:
        json_response.append(
            {
                'name': customer.name,
                'id': customer.id
            }
        )

    return HttpResponse(json.dumps(json_response), mimetype='application/javascript')

def save(request):
    if request.is_ajax():
        customer = CustomerDecoder().decode(request.raw_post_data)
        try:
            customer.save()
        except Exception, e:
            uid = uuid.uuid4()
            logger.error(message.msgWithUUID(uid, "Error saving customer"), e)
            return message.buildError("Error saving customer", uid)

        response = {}
        response['id'] = customer.id
        response['name'] = customer.name

        return HttpResponse(json.dumps(response), 'application/json')
  